package com.example.hdx.service.Impl;


import com.baomidou.mybatisplus.core.assist.ISqlRunner;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.hdx.entity.Cart;
import com.example.hdx.entity.Product;
import com.example.hdx.mapper.CartMapper;
import com.example.hdx.service.CartService;
import com.example.hdx.service.ProductService;
import com.example.hdx.util.FwResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    @Autowired//主动注入，作用是把Spring容器创建的对象赋值给下面定义的对象
    ProductService productService;
    @Autowired
    private CartMapper cartMapper;

    @Override
    public List<Cart> getCartWithProductDetails(Long userId) {
        List<Cart> carts = cartMapper.selectList(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId));

        for (Cart cart : carts) {
            Product product = productService.getById(cart.getProductId());
            cart.setProduct(product);
        }

        return carts;
    }

    @Override
    public FwResult<Boolean> addToCart(Long userId, Long productId, Integer quantity) {
        try {
            // 1. 检查商品是否存在
            Product product = productService.getById(productId);
            if (product == null) {
                return FwResult.failedMsg("商品不存在");
            }

            // 2. 检查购物车是否已有该商品
            Cart existCart = this.lambdaQuery()
                    .eq(Cart::getUserId, userId)
                    .eq(Cart::getProductId, productId)
                    .one();

            if (existCart != null) {
                // 3. 更新数量
                existCart.setQuantity(existCart.getQuantity() + quantity);
                boolean updated = this.updateById(existCart);
                return updated ? FwResult.ok(true) : FwResult.failedMsg("更新购物车失败");
            } else {
                // 4. 新增购物车项
                Cart cart = new Cart();
                cart.setUserId(userId);
                cart.setProductId(productId);
                cart.setQuantity(quantity);
                cart.setSelected(true);
                boolean saved = this.save(cart);
                return saved ? FwResult.ok(true) : FwResult.failedMsg("添加购物车失败");
            }
        } catch (Exception e) {
            log.error("添加购物车异常", e);
            return FwResult.failedMsg("系统异常");
        }
    }

//    @Override
//    public FwResult<List<Cart>> getUserCart(Long userId) {
//        try {
//            List<Cart> cartList = baseMapper.getCartWithProducts(userId);
//            return FwResult.ok(cartList);
//        } catch (Exception e) {
//            log.error("获取购物车列表异常", e);
//            return FwResult.failedMsg("获取购物车列表失败");
//        }
//    }
    @Override
    public FwResult<List<Cart>> getUserCart(Long userId) {
        List<Cart> carts = this.lambdaQuery()
                .eq(Cart::getUserId, userId)
                .list();

        for (Cart cart : carts) {
            Product product = productService.getById(cart.getProductId());
            cart.setProduct(product);
        }

        return FwResult.ok(carts);
    }

    @Override
    public FwResult<Boolean> updateQuantity(Long userId, Long productId, Integer quantity) {
        try {
            // 1. 参数校验
            if (userId == null || productId == null || quantity == null) {
                return FwResult.failedMsg("参数不能为空");
            }

            if (quantity <= 0) {
                return FwResult.failedMsg("商品数量必须大于0");
            }

            // 2. 检查商品是否存在
            Product product = productService.getById(productId);
            if (product == null) {
                return FwResult.failedMsg("商品不存在");
            }

            // 3. 查找购物车项
            Cart cart = this.lambdaQuery()
                    .eq(Cart::getUserId, userId)
                    .eq(Cart::getProductId, productId)
                    .one();

            if (cart == null) {
                return FwResult.failedMsg("购物车中不存在该商品");
            }

            // 4. 更新数量
            cart.setQuantity(quantity);
            boolean updated = this.updateById(cart);

            return updated ? FwResult.ok(true) : FwResult.failedMsg("更新购物车失败");

        } catch (Exception e) {
            log.error("更新购物车数量异常", e);
            return FwResult.failedMsg("系统异常");
        }
    }

    @Override
    public FwResult<Boolean> removeFromCart(Long userId, Long productId) {
        try {
            // 1. 参数校验
            if (userId == null || productId == null) {
                return FwResult.failedMsg("参数不能为空");
            }

            // 2. 查找购物车项
            Cart cart = this.lambdaQuery()
                    .eq(Cart::getUserId, userId)
                    .eq(Cart::getProductId, productId)
                    .one();

            if (cart == null) {
                return FwResult.failedMsg("购物车中不存在该商品");
            }

            // 3. 删除购物车项
            boolean removed = this.removeById(cart.getId());

            return removed ? FwResult.ok(true) : FwResult.failedMsg("删除购物车商品失败");

        } catch (Exception e) {
            log.error("删除购物车商品异常", e);
            return FwResult.failedMsg("系统异常");
        }
    }

    @Override
    public FwResult<Boolean> updateSelected(Long userId, Long productId, Boolean selected) {
        try {
            // 1. 参数校验
            if (userId == null || productId == null || selected == null) {
                return FwResult.failedMsg("参数不能为空");
            }

            // 2. 查找购物车项
            Cart cart = this.lambdaQuery()
                    .eq(Cart::getUserId, userId)
                    .eq(Cart::getProductId, productId)
                    .one();

            if (cart == null) {
                return FwResult.failedMsg("购物车中不存在该商品");
            }

            // 3. 更新选中状态
            cart.setSelected(selected);
            boolean updated = this.updateById(cart);

            return updated ? FwResult.ok(true) : FwResult.failedMsg("更新商品选中状态失败");

        } catch (Exception e) {
            log.error("更新商品选中状态异常", e);
            return FwResult.failedMsg("系统异常");
        }
    }

    @Override
    public FwResult<Boolean> selectAll(Long userId, Boolean selected) {
        try {
            // 1. 参数校验
            if (userId == null || selected == null) {
                return FwResult.failedMsg("参数不能为空");
            }

            // 2. 批量更新选中状态
            boolean updated = this.lambdaUpdate()
                    .eq(Cart::getUserId, userId)
                    .set(Cart::getSelected, selected)
                    .update();

            return updated ? FwResult.ok(true) : FwResult.failedMsg("更新商品选中状态失败");

        } catch (Exception e) {
            log.error("批量更新商品选中状态异常", e);
            return FwResult.failedMsg("系统异常");
        }
    }


    // 其他方法实现...
}